package time_consume;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

public class ReducerDemo extends Reducer<Text, BeanDemo, Text, BeanDemo> {
    //此处使用ArrayList动态集合，可以自动管理时间长度，无需手动设置

    @Override
    protected void reduce(Text key, Iterable<BeanDemo> values, Reducer<Text, BeanDemo, Text, BeanDemo>.Context context)
            throws IOException, InterruptedException {
        BigDecimal total = BigDecimal.ZERO;
        List<Long> timeList = new ArrayList<>();
        //求同一用户消费总和，创建一个数组获得时间戳总和
        for (BeanDemo value : values) {
            total = total.add(value.getPrice());
            long time = Long.parseLong(value.getTime());
            time *= 1000;
            //将毫秒数值保存在timeList中
            timeList.add(time);
        }
        //对timeList进行排序,对于自然顺序（从小到大）排序可以直接传递null就行
        List<String> timeArr = new ArrayList<>();
        timeList.sort(null);
        for (long timeTmp : timeList) {
            Instant instant = Instant.ofEpochMilli(timeTmp);
            LocalDateTime date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            timeArr.add(date.toString());
        }

        //将String类型的数值按照','区分合并为String类型
        String timePrint;
        timePrint = String.join("\t", timeArr);
        //输出
        context.write(key, new BeanDemo(timePrint, total));

    }
}